import { createRouter, createWebHashHistory } from "vue-router";
import Cookies from "js-cookie";

const routes = [
  {
    path: "/",
    name: "home",
    component: () => import("../views/HomeView.vue"),
  },
  {
    path: "/details",
    name: "details",
    component: () => import("../views/Details.vue"),
  },
  {
    path: "/answer",
    name: "answer",
    component: () => import("../views/Answer.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/LoginView.vue"),
  },
  {
    path: "/product",
    name: "product",
    component: () => import("../views/product/index.vue"),
  },
  {
    path: "/admin",
    name: "admin",
    component: () => import("../views/AdminView.vue"),
    meta: {
      isRelease: true,
    },
    children: [
      {
        path: "TerritoryManagement",
        name: "TerritoryManagement",
        component: () => import("../components/TerritoryManagement.vue"),
      },
      {
        path: "AnswerManagement",
        name: "AnswerManagement",
        component: () => import("../components/AnswerManagement.vue"),
      },
      {
        path: "productAdmin",
        name: "productAdmin",
        component: () => import("../components/productAdmin.vue"),
      },
    ],
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
  if (Cookies.get("token") != null) {
    next();
  } else {
    if (to.meta.isRelease) {
      next("/login");
    } else {
      next();
    }
  }
});

export default router;
